import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: '加油',
    nextId: 6,
    activeIndex: 2
  },
  mutations: {
    initList (state, list) {
      state.list = list
    },
    viewInputValue (state, value) {
      state.inputValue = value
    },
    addItem (state) {
      state.list.push({
        id: state.nextId,
        info: state.inputValue,
        done: false
      })
      state.nextId++
      state.inputValue = ''
    },
    removeItem (state, id) {
      const i = state.list.findIndex(x => x.id === id)
      state.list.splice(i, 1)
    },
    changeDone (state, id) {
      const index = state.list.findIndex(i => i.id === id)
      state.list[index].done = !state.list[index].done
    },
    clearDone (state) {
      state.list = state.list.filter(x => !x.done)
    },
    setActiveIndex (state, index) {
      state.activeIndex = index
    }
  },
  actions: {
    async getList ($store) {
      const { data } = await axios.get('/list.json')
      $store.commit('initList', data)
    }
  },
  getters: {
    unDone (state) {
      // 统计未完成的数量 优化前
      // const unDoneArr = state.list.filter(i => {
      //   return i.done === false
      // })
      // return unDoneArr.length
      return state.list.filter(x => !x.done).length
    },
    filterList (state) {
      if (state.activeIndex === 1) return state.list.filter(x => !x.done)
      if (state.activeIndex === 2) return state.list.filter(x => x.done)
      return state.list
    }
  }
})